package com.newbee.sustainability.plugin.util;

import com.newbee.sustainability.plugin.annotation.Column;
import com.newbee.sustainability.plugin.annotation.Id;
import com.newbee.sustainability.plugin.annotation.Table;
import com.newbee.sustainability.plugin.exception.PojoStructureException;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Description：pojo反射类
 * Date：2018/12/27
 * Time：11:31
 *
 * @author Likailun
 */
public class ReflectUtil {
    public static String tableName(Class<?> tclass) throws Exception {
        Table table = tclass.getAnnotation(Table.class);
        if (!Objects.isNull(table)) {
            return table.name();
        } else {
            throw new PojoStructureException("undefine POJO @Table, need Tablename(@Table(name))");
        }
    }

    public static Map<String, String> id(Class<?> clazz) {
        Map<String, String> map = new HashMap<>();
        for (Field field : clazz.getDeclaredFields()) {
            if (!field.isAnnotationPresent(Id.class)) {
                continue;
            }
            map.put(MyBatisUtil.KEY_ID_FIELD, field.getName());
            Column column = field.getAnnotation(Column.class);
            if (column == null || "".equals(column.name().trim())) {
                map.put(MyBatisUtil.KEY_ID_COLUMN, field.getName());
                return map;
            }
            map.put(MyBatisUtil.KEY_ID_COLUMN, column.name());
            return map;

        }
        throw new RuntimeException("POJO 没有定义 @Id");
    }


}
